import { api } from '../../utils/api';

Page({
  data: {
    qrCode: '',
    qrCodeUrl: '',
    isScanMode: false,
    currentUser: null as any,
  },

  onLoad(options: any) {
    const action = options.action;
    if (action === 'scan') {
      this.setData({
        isScanMode: true,
      });
      this.scanQRCode();
    } else {
      this.generateMyQRCode();
    }
  },

  async generateMyQRCode() {
    try {
      const res: any = await api.getCurrentUser();
      if (res.success && res.user) {
        this.setData({
          currentUser: res.user,
          qrCode: res.user.qrCode || `QR_${res.user.username}_${Date.now()}`,
        });
        // 生成二维码图片（这里简化处理，实际应使用二维码生成库）
        // 使用在线二维码生成服务
        const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${this.data.qrCode}`;
        this.setData({
          qrCodeUrl,
        });
      }
    } catch (error) {
      console.error('生成二维码失败:', error);
      wx.showToast({
        title: '生成失败',
        icon: 'none',
      });
    }
  },

  scanQRCode() {
    wx.scanCode({
      onlyFromCamera: false,
      success: async (res) => {
        const qrCode = res.result;
        wx.showLoading({
          title: '添加中...',
        });

        try {
          const result: any = await api.addContact(qrCode);
          if (result.success) {
            wx.hideLoading();
            wx.showToast({
              title: '已发送添加请求',
              icon: 'success',
            });
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          } else {
            wx.hideLoading();
            wx.showToast({
              title: result.message || '添加失败',
              icon: 'none',
            });
          }
        } catch (error) {
          wx.hideLoading();
          wx.showToast({
            title: '添加失败',
            icon: 'none',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '扫码失败',
          icon: 'none',
        });
      },
    });
  },

  onSaveQRCode() {
    if (!this.data.qrCodeUrl) {
      wx.showToast({
        title: '二维码未生成',
        icon: 'none',
      });
      return;
    }

    wx.downloadFile({
      url: this.data.qrCodeUrl,
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
            });
          },
          fail: () => {
            wx.showToast({
              title: '保存失败',
              icon: 'none',
            });
          },
        });
      },
      fail: () => {
        wx.showToast({
          title: '下载失败',
          icon: 'none',
        });
      },
    });
  },
});

